/*!
\copyright  Copyright (c) 2024 Qualcomm Technologies International, Ltd.
            All Rights Reserved.
            Qualcomm Technologies International, Ltd. Confidential and Proprietary.
\file
\brief      Support for proximity where driver is supplied by sensor subsystem
*/

#ifdef HAVE_SENSORSS

#include <panic.h>
#include <stdlib.h>
#include <logging.h>
#include <pl_timers/pl_timers.h>
#include "adk_log.h"
#include "proximity.h"
#include "proximity_sensorss.h"
#include "proximity_config.h"
#include "app_sensor.h"


LOGGING_PRESERVE_MESSAGE_ENUM(proximity_messages)
/*!< Task information for proximity sensor */
proximityTaskData app_proximity;

/* Handle the message from the sensorSS to indicate if the sensor is in proximity or not */
static void proximitySensorSs_MessageHandler(Task task, MessageId  id, Message msg)
{
    proximityTaskData *proximity = (proximityTaskData *) task;
    
    bool proximity_state = ((const SENSOR_SS_PROX_EVENT_T *)msg)->prox_data;
    if (proximity->clients != NULL)
    {
        switch(id)
        {
            case SENSOR_SS_PROX_EVENT:
            {
                if (!proximity_state)
                {
                    DEBUG_LOG_VERBOSE("proximitySensorSs_MessageHandler not in proximity");
                    TaskList_MessageSendId(proximity->clients, PROXIMITY_MESSAGE_NOT_IN_PROXIMITY);
                }
                else
                {
                    DEBUG_LOG_VERBOSE("proximitySensorSs_MessageHandler in proximity");
                    TaskList_MessageSendId(proximity->clients, PROXIMITY_MESSAGE_IN_PROXIMITY);
                }
            }        
        break;

        /* Unknown ID */
        default:
            DEBUG_LOG_VERBOSE("Unknown ID from proximity, %d", id);
        break;
        }
    }

}

bool appProximityClientRegister(Task task)
{
    proximityTaskData *prox = ProximityGetTaskData();

    if (NULL == prox->clients)
    {
        prox->config = NULL;
        prox->state = NULL;
        prox->clients = TaskList_Create();
        prox->task.handler = proximitySensorSs_MessageHandler;
    }

    /* We assume that the sensor is not in proximity, and the sensorSS will send the correct status when powered */
    DEBUG_LOG_INFO("HX3002 sensor  not in proximity");
    MessageSend(task, PROXIMITY_MESSAGE_NOT_IN_PROXIMITY, NULL);
 
    DEBUG_LOG_VERBOSE("Proximity Client registered");

    return TaskList_AddTask(prox->clients, task);
}

void appProximityClientUnregister(Task task)
{
    proximityTaskData *prox = ProximityGetTaskData();
    TaskList_RemoveTask(prox->clients, task);
    if (0 == TaskList_Size(prox->clients))
    {
        TaskList_Destroy(prox->clients);
        prox->clients = NULL;
    }
}
/* This function is to switch on/off sensor for power saving*/
void appProximityEnableSensor(Task task, bool enable)
{
    UNUSED(task);
    UNUSED(enable);
}

Task ProximitySensorGetTask(void)
{
    return &app_proximity.task;
}

#endif /* HAVE_SENSORSS */